import math
import datetime

import simplejson

from user.models import user_manger
from .models import cont_manger, post_manger, Post, Content
from utils import KEY, auth_decorator, query_get, jsonify, check_value, get_token

from django.views.generic import View
from django.db.transaction import atomic
from django.http import HttpRequest, JsonResponse


class MainView(View):
    @auth_decorator
    def get(self, request: HttpRequest):
        try:
            # TODO page,size这些参数以后就都固定下来，所以此处就不在修改完善check_value
            # TODO 与query_get函数的缺省值必须配置的问题
            query = query_get(request.GET, page=1, size=2, priority=3, hard=0, type_func=int)
            payload = getattr(self, 'payload')
            user_id = payload['id']
            priority = check_value(query.priority, '1')

            total_posts = post_manger\
                .filter(user_id=user_id)\
                .filter(priority__lte=priority)\
                .count()

            size = check_value(query.size, "2")
            page = check_value(query.page, f"1-{math.ceil(total_posts//size)}")
            start = size*(page-1)

            # TODO 具体设计优先级(困难程度)的策略, 一至五颗星，星越多越难
            posts = post_manger.filter(user_id=user_id).filter(priority__lte=priority)[start: start+size]
            print(posts.query)
            # print(posts)
            token = get_token(user_manger.get(pk=user_id))
            return JsonResponse({'posts': [jsonify(post, exclude='user') for post in posts],
                                 'token': token
                                 }, status=200)
        except Exception as e:
            print(e)
        return JsonResponse({}, status=400)

    @auth_decorator
    def post(self, request: HttpRequest):

        try:
            payload = getattr(self, 'payload')
            user_id = payload['id']
            user = user_manger.get(pk=user_id)
            if not user:
                return JsonResponse({}, status=400)

            # TODO 由于不知道时间的格式，暂时先未完成格式的转换，用的都是第一次post的时间
            payload = simplejson.loads(request.body)
            now = int(datetime.datetime.now().timestamp())

            postdate = now

            title = payload['title']
            todo_date = payload.get('todo_date', now)
            will_complete_date = payload.get('will_complete_date', now)
            priority = payload['priority']
            cont = payload['content']

            post = Post(user_id=user_id)
            content = Content()
            with atomic():
                user.post_count_all += 1

                post.title = title
                post.todo_date = todo_date
                post.will_complete_date = will_complete_date
                post.priority = priority
                post.postdate = postdate
                post.todo_count = user.post_count_all
                post.save()

                content.post = post
                content.content = cont
                content.save()
                user.save()
            token = get_token(user)

            return JsonResponse({'ok': 'create ok', 'token': token})
        except Exception as e:
            print(e)
            return JsonResponse({'error': '用户输入错误'}, status=400)

    def delete(self, request: HttpRequest):
        pass

    def put(self, request: HttpRequest):
        pass
